<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;

use app\api\error\User as CommonUser;

/**
 * 商品接口逻辑
 */
class Goods extends ApiBase
{
	/**
	 * 二维码
	 */
	public function erweima($data){
		if(empty($data['gid']) || empty($data['invitation'])){
			return CommonUser::$paramError;
		}
		$qr_data  = create_qrcode('http://www.chinawylm.com/wap/#/product/detail?gid='.$data['gid'].'&share='.$data['invitation']);
		$pic=db('goods')->where('id',$data['gid'])->value('share_id');
		if(empty($pic)){
			return ['code' => 1010001, API_MSG_NAME => '未上传商品分享背景图！'];
		}
		$img='e_'.$data['gid'].'_'.$data['invitation'].'.png';
		$gData=array(
			'pic'=>$qr_data['path'],
			'bg'=>substr(get_picture_url($pic),1)
		);
		createSharePngs($gData,'./qrcode/'.$img);
//		if(!createSharePngs($gData,'./qrcode/'.$img)){
//			return ['code' => 1010001, API_MSG_NAME => '请上传正确背景图！'];
//		}
		return '/qrcode/'.$img;
	}
	/**
	 * 微信分享
	 */
	public function wxShare($data){

		import("wechat.Jssdk");
		$jssdk  = new \Jssdk('wx3f6de126bb13ca05','8fb3d29df80e1042f182c7787d748ed7',urldecode($data['url']));
		$signPackage = $jssdk->getSignPackage();
		return $signPackage;
	}
	/**
	 * 商品订单列表
	 */
	public function userOrderInfo($data)
	{
		$where=" user_id=".$data['user_id'];
		$addressinfo=db('address')->where($where)->order("stat desc,id desc")->find();
		$goodsinfo=db('goods')->field('title,img_id,money,catid')->where('id',$data['gid'])->find();
		$goodsinfo['img']=get_picture_url($goodsinfo['img_id']);
		$num=$data['num'];
		$goodstype=$data['goodstype'];
		$list=compact('addressinfo','goodsinfo','num','goodstype');
		return $list;
	}
	/**
	 * 查看核销码
	 */
	public function orderCode($data)
	{
		$where=['a.user_id'=>$data['user_id'],'a.id'=>$data['id']];
		$info=db('order_info')->alias('a')->field('a.*,b.pay')->join('order_goods b',' b.order_sn=a.order_sn')->where($where)->find();
		$ginfo=db('goods')->field('user_id,invalid_time,start_time,province,city,county,address,phone')->where('id',$info['gid'])->find();
		//$dinfo=db('dian')->field('province,city,county,address,phone,title')->where('user_id',$ginfo['user_id'])->find();
		$info['dinfo']=$ginfo;
		$info['invalid_time']=$ginfo['invalid_time'];
		//$info['dz']=$dinfo['province'].$dinfo['city'].$dinfo['county'].$dinfo['address'];
		if(empty($info)){
			return CommonUser::$paramError;
		}
		if(empty($info['invitation'])){
			$code=initcode();
			$is=db('order_info')->where(['invitation'=>$code])->value('id');
			if(!empty($is)){
				$code=initcode();
			}
			$res=db('order_info')->where(['user_id'=>$data['user_id'],'id'=>$data['id']])->update(['invitation'=>$code]);
			if($res != false){
				$info['invitation']=$code;
				return $info;
			}else{
				return CommonUser::$paramError;
			}
		}else{
			return $info;
		}

	}
	/**
	 * 消费券使用
	 */
	public function opOrder($param){
		db('order_info')->startTrans();
		$info=db('order_info')->field('user_id,gid,danjia,num,order_sn,tid')->where(['gid'=>$param['gid'],'invitation'=>$param['invitation']])->find();
		$ginfo=db('goods')->field('user_id,city,county,bl,btbl,lrbl,pid,invalid_time,start_time,zt_money,jt_money')->where('id',$param['gid'])->find();
		if(empty($info) || $ginfo['user_id'] != $param['user_id']){
			return CommonUser::$paramError;
		}
		if(!empty($ginfo['start_time']) && strtotime($ginfo['start_time']) > time()){
			return CommonUser::$yhqErrors;
		}
		if(strtotime($ginfo['invalid_time']) < time()){
			return CommonUser::$yhqError;
		}
		if($info['tid']){
			$tjid=db('user')->where('id',$info['user_id'])->value('tjid');
			if(!empty($tjid)){
				moneyyj_log($ginfo['zt_money'],$tjid,23,$info['user_id'],$info['order_sn']);
				$tjjid=db('user')->where('id',$tjid)->value('tjid');
				if(!empty($tjjid)){
					moneyyj_log($ginfo['jt_money'],$tjjid,24,$info['user_id'],$info['order_sn']);
				}
			}
		}
		moneyyj_log($info['danjia']*$info['num']*$ginfo['bl'],$ginfo['user_id'],17,$info['user_id']);
		//fenrun($info['user_id'],$ginfo['user_id'],$info['danjia']*$info['num'],$ginfo['lrbl'],$ginfo['btbl'],$ginfo['bl'],$ginfo['city'],$ginfo['county'],$tjid,$ginfo['pid']);
		$res=db('order_info')->where(['gid'=>$param['gid'],'invitation'=>$param['invitation']])->update(['stat'=>2,'sh_time'=>date('Y-m-d H:i:s')]);
		if($res != false){
			db('order_info')->commit();
			return $this->apiReturn();
		}else{
			db('order_info')->rollback();
			return CommonUser::$paramError;
		}
	}
	/**
	 * 优惠券列表
	 */
	public function yhqList($data)
	{
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where="b.stat=1 and a.is_xx=1 and b.user_id=".$data['user_id'];
		if(!empty($data['stat'])){
			$where.=" and a.stat=".$data['stat'];
		}
		$list=db('order_info')->alias('a')->field('a.*,b.pay')->join('order_goods b',' b.order_sn=a.order_sn')->where($where)->limit($page,$list_rows)->order('a.stat asc,a.id desc')->select();
		foreach($list as $k=>$v){
			$list[$k]['invalid_time']=db('goods')->where('id',$v['gid'])->value('invalid_time');
		}
		return $list;
	}
	/**
	 * 优惠券列表
	 */
	public function serviceOrderLists($data)
	{
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$arr=db('goods')->where(['user_id'=>$data['user_id'],'is_xx'=>1])->column('id');
		$str=implode(',',$arr);
		$where=" a.stat>0 and a.is_xx=1 and b.stat=1 and a.gid IN(".$str.") ";
		if(!empty($data['keywords'])){
			$where.=" and a.invitation='".$data['keywords']."'";
		}
		$list=db('order_info')->alias('a')->field('a.*,b.pay,b.add_time')->join('order_goods b',' b.order_sn=a.order_sn')->where($where)->limit($page,$list_rows)->order('a.stat asc,a.id desc')->select();
		foreach($list as $k=>$v){
			$list[$k]['invalid_time']=db('goods')->where('id',$v['gid'])->value('invalid_time');
		}
		return $list;
	}
	/**
	 * 商品列表
	 */
	public function goodsCatLists($data)
	{
		$dlist=db('goods_cat')->where('pid',$data['catid'])->select();
		foreach($dlist as $key=>$val){
			$dlist[$key]['img']=get_picture_url($val['img_id']);
		}
		$pid=db('goods_cat')->where('id',$data['catid'])->value('pid');
		if(!empty($pid)){
			$goodslist=db("goods")->field('id,title,ftitle,img_id,money,max_money,btbl,catid,pid')->where("status=1 and (pid=".$data['catid']." or catid=".$data['catid'].")")->limit(50)->order("sort desc")->select();
			foreach($goodslist as $k=>$v){
				$goodslist[$k]['img']=get_picture_url($v['img_id']);
				$goodslist[$k]['jsbl']=$v['btbl']*5;
			}
		}else{
			$a=db('goods_cat')->where('pid',$data['catid'])->column('id');
			$str=implode(',',$a);
			$goodslist=db("goods")->field('id,title,ftitle,img_id,money,max_money,btbl,catid,pid')->where("status=1 and (pid IN (".$str.") or catid IN (".$str.") )")->limit(50)->order("sort desc")->select();
			foreach($goodslist as $k=>$v){
				$goodslist[$k]['img']=get_picture_url($v['img_id']);
				$goodslist[$k]['jsbl']=$v['btbl']*5;
			}
			$pid=$data['catid'];
		}
		$cid=db('ad_cat')->where('catid',$pid)->value('id');
		if(!empty($cid)){
			$bannerList=db('ad')->where(['catid'=>$cid,'status'=>1])->select();
			foreach($bannerList as $k=>$a){
				$bannerList[$k]['img']=get_picture_url($a['cover_id']);
			}
		}else{
			$bannerList=[];
		}
		$list=compact('bannerList','dlist','goodslist');
		return $list;
	}
	/**
	 * 商品列表
	 */
	public function goodsLists($data)
	{
		$dlist=db('goods_cat')->where('pid',$data['pid'])->select();
		foreach($dlist as $key=>$val){
			$dlist[$key]['img']=get_picture_url($val['img_id']);
			$list=db("goods")->where(['status'=>1,'catid'=>$val['id']])->limit(6)->order("sort desc")->select();
			foreach($list as $k=>$v){
				$img_ids_array=str2arr($v['img_ids']);
				$cont_ids_array=str2arr($v['img_ids']);
				foreach($cont_ids_array as $keys=>$va){
					$cont_ids_array[$keys]=get_picture_url($va);
				}
				foreach($img_ids_array as $keys=>$va){
					$img_ids_array[$keys]=get_picture_url($va);
				}
				$list[$k]['cont_ids_array'] =$cont_ids_array;
				$list[$k]['img_ids_array'] =$img_ids_array;
				$list[$k]['img']=get_picture_url($v['img_id']);
				$list[$k]['jsbl']=$v['btbl']*5;
			}
			$dlist[$key]['goodsList']=$list;
		}
		$cid=db('ad_cat')->where('catid',$data['pid'])->value('id');
		if(!empty($cid)){
			$bannerList=db('ad')->where(['catid'=>$cid,'status'=>1])->select();
			foreach($bannerList as $k=>$a){
				$bannerList[$k]['img']=get_picture_url($a['cover_id']);
			}
		}else{
			$bannerList=[];
		}
		$list=compact('bannerList','dlist');
		return $list;
	}
	/**
	 * 线下商家
	 */
	public function dianGoodsList($data)
	{
		$dlist=db('dian_cat')->select();
		foreach($dlist as $key=>$val){
			$dlist[$key]['img']=get_picture_url($val['img_id']);
			$where=['status'=>1,'catid'=>$val['id']];
			if(!empty($data['province'])){
				$where['province']=$data['province'];
			}
			if(!empty($data['city'])){
				$where['city']=$data['city'];
			}
			if(!empty($data['county'])){
				$where['county']=$data['county'];
			}
			$list=db("dian")->where($where)->limit(6)->order("id asc")->select();
			foreach($list as $k=>$v){
				$cont_ids_array=str2arr($v['img_ids']);
				foreach($cont_ids_array as $keys=>$va){
					$cont_ids_array[$keys]=get_picture_url($va);
				}
				$list[$k]['cont_ids_array'] =$cont_ids_array;
				$list[$k]['img']=get_picture_url($v['img_id']);
			}
			$dlist[$key]['dianList']=$list;
		}
		$bannerList=db('ad')->where(['catid'=>5,'status'=>1])->select();
		foreach($bannerList as $k=>$a){
			$bannerList[$k]['img']=get_picture_url($a['cover_id']);
		}
		$list=compact('bannerList','dlist');
		return $list;
	}
	/**
	 * 商品订单列表
	 */
	public function userOrderList($data)
	{
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" stat=1 ";
		if(!empty($data['user_id'])){
			$where.=" and user_id=".$data['user_id'];
		}
		if(!empty($data['getid'])){
			$where.=" and getid=".$data['getid'];
		}
		$list=db('order')->where($where)->limit($page,$list_rows)->order("add_time desc")->select();
		foreach($list as $k=>$v){
			$info=db('user')->field('username,name')->where('id',$v['getid'])->find();
			$list[$k]['username']=$info['username'];
			$list[$k]['name']=$info['name'];
			$list[$k]['title']=db('dian')->where('user_id',$v['getid'])->value('title');
			$infos=db('user')->field('username,name')->where('id',$v['user_id'])->find();
			$list[$k]['susername']=$infos['username'];
			$list[$k]['sname']=$infos['name'];
		}
		return $list;
	}
	/**
	 * 确认收货
	 */
	public function qrsh($param){
		$stat=db('order_goods')->where(['order_sn'=>$param['order_sn'],'user_id'=>$param['user_id']])->value('stat');
		if($stat != 1){
			return CommonUser::$paramError;
		}
		db('order_info')->startTrans();
		$info=db('order_info')->field('gid,danjia,num')->where(['gid'=>$param['gid'],'order_sn'=>$param['order_sn']])->find();
		$ginfo=db('goods')->field('user_id,city,county,bl,btbl,lrbl,pid,zt_money,jt_money')->where('id',$info['gid'])->find();
		$tjid=db('user')->where('id',$param['user_id'])->value('tjid');
		if($ginfo['tid'] == 1 && !empty($tjid)){
			moneyyj_log($ginfo['zt_money'],$tjid,23,$param['user_id'],$param['order_sn']);
			$tjjid=db('user')->where('id',$tjid)->value('tjid');
			if(!empty($tjjid)){
				moneyyj_log($ginfo['jt_money'],$tjjid,24,$param['user_id'],$param['order_sn']);
			}
			moneyyj_log($info['danjia']*$info['num']*$ginfo['bl'],$ginfo['user_id'],17,$param['user_id']);
		}else{
			fenrun($param['user_id'],$ginfo['user_id'],$info['danjia']*$info['num'],$ginfo['lrbl'],$ginfo['btbl'],$ginfo['bl'],$ginfo['city'],$ginfo['county'],$tjid,$ginfo['pid']);
		}
		$res=db('order_info')->where(['gid'=>$param['gid'],'order_sn'=>$param['order_sn']])->update(['stat'=>2]);
		if($res != false){
			db('order_info')->commit();
			return $this->apiReturn();
		}else{
			db('order_info')->rollback();
			return CommonUser::$paramError;
		}
	}
	/**
	 * 线下订单
	 */
	public function orderAdd($param){
		db('order')->startTrans();
		$param['order_sn']='xx'.date('YmdHi').rand(10,99);
		$info=db('user')->field('moneyMy,count,xfq,tjid,passwords,salt')->where(array('id'=>$param['user_id']))->find();
		if($param['pay'] == 1){
			$password=$param['password'];
			if(empty($password)){
				return ['code' => 1010001, API_MSG_NAME => '请输入密码！'];
			}
			if($info['passwords'] != data_md5_key($password,$info['salt'])){
				return ['code' => 1010001, API_MSG_NAME => '密码错误！'];
			}
			if($param['money'] > $info['count']){
				return ['code' => 1010001, API_MSG_NAME => '现金余额不足！'];
			}
			$dinfo=db('dian')->field('bl,btbl,lrbl,city,county')->where('user_id',$param['getid'])->find();
			if(empty($dinfo)){
				return CommonUser::$paramError;
			}
			moneyyj_log($param['money']*(-1),$param['user_id'],53,$param['user_id'],'线下订单支付');
			fenrun($param['user_id'],$param['getid'],$param['money'],$dinfo['lrbl'],$dinfo['btbl'],$dinfo['bl'],$dinfo['city'],$dinfo['county'],$info['tjid']);
			$param['stat']=1;
		}elseif($param['pay'] == 2){
			$password=$param['password'];
			if(empty($password)){
				return ['code' => 1010001, API_MSG_NAME => '请输入密码！'];
			}
			if($info['passwords'] != data_md5_key($password,$info['salt'])){
				return ['code' => 1010001, API_MSG_NAME => '密码错误！'];
			}
			if($param['money'] > $info['moneyMy']){
				return ['code' => 1010001, API_MSG_NAME => '现金余额不足！'];
			}
			$dinfo=db('dian')->field('bl,btbl,lrbl,city,county')->where('user_id',$param['getid'])->find();
			if(empty($dinfo)){
				return CommonUser::$paramError;
			}
			moneyyj_log($param['money']*(-1),$param['user_id'],3,$param['user_id'],'线下订单支付');
			fenrun($param['user_id'],$param['getid'],$param['money'],$dinfo['lrbl'],$dinfo['btbl'],$dinfo['bl'],$dinfo['city'],$dinfo['county'],$info['tjid']);
			$param['stat']=1;
		}elseif($param['pay'] == 3){
			$password=$param['password'];
			if(empty($password)){
				return ['code' => 1010001, API_MSG_NAME => '请输入密码！'];
			}
			if($info['passwords'] != data_md5_key($password,$info['salt'])){
				return ['code' => 1010001, API_MSG_NAME => '密码错误！'];
			}
			if($param['money'] > $info['xfq']){
				return ['code' => 1010001, API_MSG_NAME => '现金余额不足！'];
			}
			$dinfo=db('dian')->field('bl,btbl,lrbl,city,county')->where('user_id',$param['getid'])->find();
			if(empty($dinfo)){
				return CommonUser::$paramError;
			}
			moneyyj_log($param['money']*(-1),$param['user_id'],102,$param['user_id'],'线下订单支付');
			fenrun($param['user_id'],$param['getid'],$param['money'],$dinfo['lrbl'],$dinfo['btbl'],$dinfo['bl'],$dinfo['city'],$dinfo['county'],$info['tjid']);
			$param['stat']=1;
		}elseif($param['pay'] == 4){

		}elseif($param['pay'] == 5){

		}
		$param['add_time']=date('Y-m-d H:i:s');
		$res=db('order')->insert($param);
		if($res != false){
			db('order')->commit();
			if($param['pay'] !=4 && $param['pay'] != 5){
				return $this->apiReturn();
			}else{
				return $param['order_sn'];
			}
		}else{
			db('order')->rollback();
			return CommonUser::$paramError;
		}
	}
	/**
	 * 地址添加编辑
	 */
	public function addressEdit($param){
		if($param['stat'] == 1){
			db('address')->where('user_id',$param['user_id'])->update(['stat'=>0]);
		}
		if(empty($param['id'])){
			$res=db('address')->insert($param);
		}else{
			$res=db('address')->where('id='.$param['id'])->update($param);
		}
		if($res != false){
			return $this->apiReturn();
		}else{
			return CommonUser::$paramError;
		}
	}
	/**
	 * 地址删除
	 */
	public function addressDel($param){
		$res=db('address')->where(['user_id'=>$param['user_id'],'id'=>$param['id']])->delete();
		if($res != false){
			return $this->apiReturn();
		}else{
			return CommonUser::$paramError;
		}
	}
	/**
	 * 地址列表
	 */
	public function getAddressList($data)
	{
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" user_id = ".$data['user_id'];
		$list=db("address")->where($where)->limit($page,$list_rows)->order("stat desc,id desc")->select();
		return $list;
	}
	/**
	 * 店铺列表
	 */
	public function dianList($data)
	{
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" status = 1 ";
		if(!empty($data['catid'])){
			$where.=" and catid=".$data['catid'];
		}
		if(!empty($data['province'])){
			$where.=" and province='".$data['province']."'";
		}
		if(!empty($data['city'])){
			$where.=" and city='".$data['city']."'";
		}
		if(!empty($data['county'])){
			$where.=" and county='".$data['county']."'";
		}
		if(!empty($data['keywords'])){
			$keywords=$data['keywords'];
			$where.=" and title like '%$keywords%'";
		}
		$list=db("dian")->field("*,(round(6367000 * 2 * asin(sqrt(pow(sin(((x * pi()) / 180 - (".$data['x']." * pi()) / 180) / 2), 2) + cos((".$data['x']." * pi()) / 180) * cos((x * pi()) / 180) * pow(sin(((y * pi()) / 180 - (".$data['y']." * pi()) / 180) / 2), 2))))) AS distance")->where($where)->limit($page,$list_rows)->order("distance asc")->select();
		foreach($list as $k=>$v){
			$cont_ids_array=str2arr($v['img_ids']);
			foreach($cont_ids_array as $key=>$va){
				$cont_ids_array[$key]=get_picture_url($va);
			}
			$list[$k]['cont_ids_array'] =$cont_ids_array;
			$list[$k]['img']=get_picture_url($v['img_id']);
			$list[$k]['jsbl']=$v['btbl']*5;
		}
		return $list;
	}
	/**
	 * 商品添加
	 */
	public function goodsIndex($data)
	{
		$bannerList=db('ad')->where(['catid'=>3,'status'=>1])->select();
		$goodscat=db('goods_cat')->where('pid',0)->order('sort asc')->select();
		foreach($goodscat as $k=>$a){
			$goodscat[$k]['img']=get_picture_url($a['img_id']);
		}
		foreach($bannerList as $k=>$a){
			$bannerList[$k]['img']=get_picture_url($a['cover_id']);
		}
		$list=compact('bannerList','goodscat');
		return $list;
	}
	/**
     * 商品订单列表
     */
	public function serviceOrderList($data)
	{
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" b.stat=1 and a.getid=".$data['user_id'];
		$list=db('order_info')->alias('a')->field('a.*,b.pay,b.add_time,b.province,b.city,b.county,b.name,b.phone,b.address')->join('order_goods b',' b.order_sn=a.order_sn')->where($where)->limit($page,$list_rows)->order('a.stat asc,a.id desc')->select();
		return $list;
	}
	/**
     * 商品订单列表
     */
	public function userAddress($data)
	{
		$where=" user_id=".$data['user_id'];
		$list=db('address')->where($where)->order("stat desc,id desc")->find();
		return $list;
	}
	/**
     * 用户门店
     */
	public function dianInfo($data)
	{
		$info=db('dian')->where("id",$data['id'])->find();
		if(!empty($info)){
			$cont_ids_array=str2arr($info['img_ids']);
			foreach($cont_ids_array as $k=>$va){
				$cont_ids_array[$k]=get_picture_url($va);
			}
			$info['cont_ids_array'] =$cont_ids_array;
			$info['img']=get_picture_url($info['img_id']);
			$info['jsbl']=$info['btbl']*5;
			$info['names']=db('user')->where('id',$info['user_id'])->value('name');
		}
		return $info;
	}
	/**
	 * 商品订单列表
	 */
	public function orderInfo($data)
	{
		if(!empty($data['getid'])){
			$info=db('order_goods')->where(["order_sn"=>$data['order_sn']])->find();
			$where=['order_sn'=>$info['order_sn'],'getid'=>$data['getid']];
		}else{
			$info=db('order_goods')->where(["order_sn"=>$data['order_sn'],'user_id'=>$data['user_id']])->find();
			$where=['order_sn'=>$info['order_sn']];
		}
		$info['goodslist']=db('order_info')->where($where)->select();
		return $info;
	}
	/**
     * 商品订单列表
     */
	public function orderList($data)
	{
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" a.is_xx=0 and b.user_id=".$data['user_id'];
		if(isset($data['stat'])){
			if($data['stat'] < 1){
				$where.=" and b.stat=".$data['stat'];
			}else{
				$where.=" and b.stat=1 and a.stat=".($data['stat']-1);
			}
		}
		//$list=db('order_goods')->field('order_sn,user_id,money,stat,add_time,zf_time')->where($where)->limit($page,$list_rows)->order("add_time desc")->select();
		$list=db('order_info')->alias('a')->field('b.order_sn,b.user_id,b.money,b.stat,b.add_time,b.zf_time')->join('order_goods b',' b.order_sn=a.order_sn')->where($where)->limit($page,$list_rows)->order("b.id desc")->select();
		foreach($list as $k=>$v){
			$info=db('order_info')->field('order_sn,title,num,danjia,stat,img,gid,catid,pid,tid,is_xx')->where('order_sn',$v['order_sn'])->select();
			$list[$k]['infolist']=$info;
		}
		return $list;
	}
	/**
     * 订单判断
	 * @param  hxname,password,pay,gids
     * @return 
     * @throws UnauthorizedException
     */
	Public function checkOrder($param){
		//var_dump($param['gids']);exit;
		$larr=htmlspecialchars_decode($param['gids']);
		$larr=str_replace("&quot;",'"',$larr);
		$a=json_decode($larr,true);
		$sum=0;
		foreach($a as $v){		
			$kc=db('goods')->where('id='.$v['gid'])->find();
			if($v['num'] > $kc['num']){
				$title=db('goods')->where('id='.$v['gid'])->value('title');
				return ['code' => 1010001, API_MSG_NAME => '商品 '.$title.' 库存不足！'];
			}	
			$dj=$kc['money'];
			$sum+=$dj*$v['num'];				
		}
		//判断是否免运费	
		$sum=$sum>0?round($sum,2):0;
		if( $sum != $param['sumprice']){
			return ['code' => 1010001, API_MSG_NAME => '支付金额不匹配'];
		}
		$info=db('user')->field('nocodea,is_service,moneyMy')->where(array('id'=>$param['user_id']))->find();
		if($info['is_service'] == 1 ){
			$pay = 2;			
		}elseif($info['is_service'] == 2 ){
			if($info['moneyMy'] < $sum){
				$pay=2;
			}else{
				$pay=1;
			}
		}else{
			$b=substr($info['nocodea'],0,-1);
			$is=db('user')->where("id IN(".$b.") and is_service=2")->order("field(id,".$b.") desc")->value('moneyMy');
			if(!empty($is) && $is >= $sum){
				$pay=1;
			}else{
				$pay=2;
			}
		}						
		return $pay;		
	}
	/**
     * 商品生成订单
	 * @param  user_id,password,pay,gids
     * @return 
     * @throws UnauthorizedException
     */
	Public function cartOrder($param){
		//$larr=htmlspecialchars_decode($param['gids']);
		//$larr=str_replace("&quot;",'"',$larr);
		//$a=json_decode($larr,true);
		$pay=$param['pay'];
		$sum=0;
		$yunf=0;
		$isxx=0;
		db('order_goods')->startTrans();
		$order_sn='gs'.date('ymdhis',time()).rand(10,99);
		foreach($param['gids'] as $v){
			$kc=db('goods')->field('num,money,img_id,title,user_id,pid,catid,is_xx,tid')->where('id='.$v['gid'])->find();
			if($kc['is_xx']==0 && empty($param['aid'])){
				return ['code' => 1010001, API_MSG_NAME => '请选择收货信息！'];
			}
			if($v['num'] > $kc['num']){
				$title=db('goods')->where('id='.$v['gid'])->value('title');
				return ['code' => 1010001, API_MSG_NAME => '商品 '.$title.' 库存不足！'];
			}	
			$dj=$kc['money'];
			$sum+=$dj*$v['num'];
			//运费
			/*if(!empty($kc['is_free_shipping']) && !empty($addressInfo)){
				$arr=array($addressInfo['province'],$addressInfo['city'],$addressInfo['county']);
				$isyunf=$this->getYunf($kc['template_id'],$v,$arr);
				if($isyunf !== false){
					$yunf+=$isyunf;
				}else{
					echo json_encode(array('error'=>1,'html'=>'系统错误，请稍后重试'));
					exit;
				}			
			}*/
			$content=array(
				'order_sn'=>$order_sn,
				'user_id'=>$param['user_id'],
				'img'=>get_picture_url($kc['img_id']),
				'title'=>$kc['title'],
				'gid'=>$v['gid'],
				'getid'=>$kc['user_id'],
				'num'=>$v['num'],
				'goodstype'=>$v['goodstype'],
				'catid'=>$kc['catid'],
				'pid'=>$kc['pid'],
				'tid'=>$kc['tid'],
				'is_xx'=>$kc['is_xx'],
				'danjia'=>$dj
			);
			if($kc['is_xx'] == 1){
				$content['stat']=1;
				$isxx=1;
			}
			db('order_info')->insert($content);					
		}
		//判断是否免运费	
		$sum=$sum+$yunf;
		$sum=$sum>0?round($sum,2):0;
		if( $sum != $param['sumprice']){
			return ['code' => 1010001, API_MSG_NAME => '支付金额不匹配'];
		}
		$cont=['pay'=>$pay,
			'user_id'=>$param['user_id'],
			'money'=>$sum,
			'order_sn'=>$order_sn,
			'yunf'=>$yunf,
			'beizhu'=>$param['beizhu'],
			'add_time'=>date('Y-m-d H:i:s')];
		if(empty($isxx)){
			$ainfo=db('address')->where(['user_id'=>$param['user_id'],'id'=>$param['aid']])->find();
			$cont['name']=$ainfo['name'];
			$cont['phone']=$ainfo['phone'];
			$cont['province']=$ainfo['province'];
			$cont['city']=$ainfo['city'];
			$cont['county']=$ainfo['county'];
			$cont['address']=$ainfo['address'];
		}
		$info=db('user')->field('moneyMy,count,xfq,passwords,salt,is_service,nocodea')->where(array('id'=>$param['user_id']))->find();
		if($pay != 4 && $pay != 5 ){
			$password=$param['password'];
			if($pay == 1){
				$moneymy=$info['count'];
				$t=53;
			}elseif($pay == 2){
				$moneymy=$info['moneyMy'];
				$t=6;
			}else{
				$moneymy=$info['xfq'];
				$t=102;
			}
			if(empty($password)){
				return ['code' => 1010001, API_MSG_NAME => '请输入密码！'];
			}
			if($info['passwords'] != data_md5_key($password,$info['salt'])){
				return ['code' => 1010001, API_MSG_NAME => '密码错误！'];
			}
			if($sum > $moneymy){
				return ['code' => 1010001, API_MSG_NAME => '余额不足！'];
			}
			$cont['stat']=1;
			$cont['zf_time']=date('Y-m-d H:i:s',time());
			moneyyj_log($sum*(-1),$param['user_id'],$t,$param['user_id'],'购买商品，积分减少');
			foreach($param['gids'] as $k=>$v){
				//减少库存
				db('goods')->where('id='.$v['gid'])->setInc('num',(-1)*$v['num']);
			}
		}else{
			$cont['stat']=0;
		}
		$res=db('order_goods')->insert($cont);			
		if($res != false){						
			//减少库存			
			db('order_goods')->commit();
			if($pay != 4 && $pay != 5){
				return $this->apiReturn();
			}else{
				return $order_sn;
			}				
		}else{
			db('order_goods')->rollback();
			return CommonUser::$paramError;
		}		
	}
	/**
     * 购物车列表
     */
	public function goodsCartList($data)
	{
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" user_id=".$data['user_id'];
		$list=db('goods_cart')->where($where)->limit($page,$list_rows)->order("add_time desc")->select();
		foreach($list as $k=>$v){
			$ginfo=db('goods')->field('title,img_id,money')->where('status=1 and id='.$v['gid'])->find();
			$list[$k]['img']=get_picture_url($ginfo['img_id']);
			$list[$k]['title']=$ginfo['title'];
			$list[$k]['money']=$ginfo['money'];
			$list[$k]['isselect']=false;
		}
		return $list;
	}
	/**
     * 加入购物车
     */
	public function goodsCart($param){	
		$is=db('goods_cart')->where("gid=".$param['gid']." and user_id=".$param['user_id'])->value('id');
		if(empty($is)){
			$param['add_time']=date('Y-m-d H:i:s');
			$res=db('goods_cart')->insert($param);
		}else{
			$res=db('goods_cart')->where('id='.$is)->setInc('num',$param['num']);
		}
		if($res != false){
			return $this->apiReturn();
		}else{
			return CommonUser::$paramError;
		}
	}
	/**
     * 删除购物车
     */
	public function goodsCartDel($param){	
		$is=db('goods_cart')->where("id=".$param['id']." and user_id=".$param['user_id'])->value('id');
		if(empty($is)){
			return CommonUser::$paramError;
		}else{
			$res=db('goods_cart')->where('id='.$param['id'])->delete();
		}
		if($res != false){
			return $this->apiReturn();
		}else{
			return CommonUser::$paramError;
		}
	}
	/**
	 * 商品详情
	 */
	public function goodsInfos($data)
	{
		header('Access-Control-Allow-Origin:*');
		$info=db('goods')->where(['id'=>$data['gid']])->find();
		if(empty($info)){
			return ['code' => 1010001, API_MSG_NAME => '该商品已下架！'];
		}
		$info['img']=get_picture_url($info['img_id']);
		$info['share']=get_picture_url($info['share_id']);
		$img_ids_array=str2arr($info['img_ids']);
		foreach($img_ids_array as $k=>$val){
			$img_ids_array[$k]=get_picture_url($val);
		}
		$cont_ids_array=str2arr($info['cont_ids']);
		foreach($cont_ids_array as $k=>$va){
			$cont_ids_array[$k]=get_picture_url($va);
		}
		$info['img_ids_array'] =$img_ids_array;
		$info['cont_ids_array'] =$cont_ids_array;
		$info['jsbl']=$info['btbl']*5;
		if(!empty($info['goodstype'])){
			$arr=[];
			$typelist=explode(',',$info['goodstype']);
			foreach($typelist as $k=>$v){
				$arr[]=explode('/',$v);
			}
			$info['typelist']=$arr;
		}
		if($info['tid'] == 1){
			$info['is_qg']=true;
		}else{
			$info['is_qg']=false;
		}
		return $info;
	}
	/**
     * 商品详情
     */
    public function goodsInfo($data)
    {
		header('Access-Control-Allow-Origin:*');
		$info=db('goods')->where(['status'=>1,'id'=>$data['gid']])->find();
		if(empty($info)){
			return ['code' => 1010001, API_MSG_NAME => '该商品已下架！'];
		}
		$info['img']=get_picture_url($info['img_id']);
		$info['share']=get_picture_url($info['share_id']);
		$img_ids_array=str2arr($info['img_ids']);
		foreach($img_ids_array as $k=>$val){
			$img_ids_array[$k]=get_picture_url($val);
		}
		$cont_ids_array=str2arr($info['cont_ids']);
		foreach($cont_ids_array as $k=>$va){
			$cont_ids_array[$k]=get_picture_url($va);
		}
		$info['img_ids_array'] =$img_ids_array;
		$info['cont_ids_array'] =$cont_ids_array;
		$info['jsbl']=$info['btbl']*5;
		if(!empty($info['goodstype'])){
			$arr=[];
			$typelist=explode(',',$info['goodstype']);
			foreach($typelist as $k=>$v){
				$arr[]=explode('/',$v);
			}
			$info['typelist']=$arr;
		}
		if($info['tid'] == 1){
			$info['is_qg']=true;
		}else{
			$info['is_qg']=false;
		}
		return $info;
    }
	/**
     * 商品列表
     */
	public function goodsList($data)
	{
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$where=" status=1 ";
		if(!empty($data['keywords'])){
			$keywords=$data['keywords'];
			$where.=" and title like '%$keywords%'";
		}
		if(!empty($data['catid'])){
			$where.=" and catid =".$data['catid'];
		}
		if(!empty($data['orders'])){
			$where.=" and orders = 1";
		}
		if(!empty($data['special'])){
			$where.=" and special = 1";
		}
		$list=db('goods')->where($where)->limit($page,$list_rows)->order("sort desc")->select();
		foreach($list as $k=>$v){
			$list[$k]['img']=get_picture_url($v['img_id']);
			$list[$k]['jsbl']=$v['btbl']*5;
		}
		return $list;
	}

}
